package server

import (
	"errors"
	"log"
	"order-module/order-rpc/initiate/mysql"
	"order-module/order-rpc/proto/good"
)

func UserRegister(in *good.UserRegisterReq) (*good.UserRegisterResp, error) {
	u := mysql.User{
		Name:     in.Name,
		Phone:    in.Phone,
		Password: in.Password,
	}
	err := u.Find(in.Phone)
	if err != nil {
		log.Println("未查询到该数据")
		return nil, errors.New("未查询到该数据")
	}
	if u.ID != 0 {
		log.Println("当前账号已经被注册")
		return nil, errors.New("当前账号已经被注册")
	}
	err = u.Create()
	if err != nil {
		log.Println("当前用户注册失败")
		return nil, errors.New("当前用户注册失败")
	}
	return &good.UserRegisterResp{
		Greet: "当前用户注册成功",
		Code:  200,
	}, nil
}

func GoodCreate(in *good.GoodCreateReq) (*good.GoodCreateResp, error) {
	m := mysql.Good{
		Name:    in.Name,
		Content: in.Content,
		Price:   float64(in.Price),
		Num:     in.Num,
		Status:  in.Status,
	}
	if in.Num > m.Num {
		log.Println("当前库存不足")
		return nil, errors.New("当前库存不足")
	}
	err := m.Create()
	if err != nil {
		log.Println("商品下单失败")
		return nil, errors.New("商品下单失败")
	}
	return &good.GoodCreateResp{
		Greet: "商品下单成功",
		Code:  200,
	}, nil
}

func GoodList(in *good.GoodListReq) (*good.GoodListResp, error) {
	m := mysql.Good{}
	li, err := m.List()
	if err != nil {
		log.Println("展示失败")
		return nil, errors.New("展示失败")
	}
	var list []*good.GoodList
	for _, g := range li {
		lists := &good.GoodList{
			Name:    g.Name,
			Content: g.Content,
			Price:   float32(g.Price),
			Num:     int64(g.Num),
			Status:  int64(g.Status),
		}
		list = append(list, lists)
	}
	return &good.GoodListResp{List: list}, nil
}

func GoodOrder(in *good.GoodOrderReq) (*good.GoodOrderResp, error) {
	o := mysql.Order{}
	err := o.Create()
	if err != nil {
		log.Println("下订单失败")
		return nil, errors.New("下订单失败")
	}
	return &good.GoodOrderResp{Success: true}, nil
}
